

from django import forms
from django.core.exceptions import ValidationError
from django.utils import timezone
from .models import Book, Author, BookLoan

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = '__all__'
    
    def clean_publish_date(self):
        publish_date = self.cleaned_data.get('publish_date')
        if publish_date and publish_date > timezone.now().date():
            raise ValidationError("Publish date cannot be in the future.")
        return publish_date

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        fields = '__all__'
    
    def clean_email(self):
        email = self.cleaned_data.get('email')
        if Author.objects.filter(email=email).exclude(pk=self.instance.pk).exists():
            raise ValidationError("An author with this email already exists.")
        return email

class BookLoanForm(forms.ModelForm):
    class Meta:
        model = BookLoan
        fields = ['book', 'user', 'due_date']
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['book'].queryset = Book.objects.filter(status='published')
    
    def clean(self):
        cleaned_data = super().clean()
        book = cleaned_data.get('book')
        user = cleaned_data.get('user')
        
        if book and user:
            active_loan = BookLoan.objects.filter(
                book=book, 
                user=user, 
                return_date__isnull=True
            ).exists()
            
            if active_loan:
                raise ValidationError("This user already has an active loan for this book.")
        
        return cleaned_data